import React, {Component} from 'react';
import Taro from '@tarojs/taro';
import {Image, ScrollView, Text, View} from "@tarojs/components";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {vcmonitor} from "../../utils/tools";
import {newHttp} from "../../utils/request";
import {RESOURCE_URL, DOUYIN_COMINORM, DOUYIN_COMSTATUS} from "../../constants/api";
import {h5Wx} from '../../utils/h5.service';
import './businessList.scss'

type PageState = {
  loadMoreStatus: "more" | "loading" | "noMore"
  tableData: any
  groupList: any
  currentIndex: any
}

export default class ProductList extends Component {
  state: PageState = {
    loadMoreStatus: 'loading',
    currentIndex: '',
    tableData: [],
    groupList: []
  }

  async UNSAFE_componentWillMount() {
    await vcmonitor(this)
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
  }

  async getStatus() {
    const status = await newHttp.get(DOUYIN_COMSTATUS)
    return status.data
  }

  async componentDidShow() {
    this.page = 1
    this.total = 0
    this.setState({tableData: await this.getData(), groupList: await this.getStatus()})
  }

  async getData() {
    const tableData = await newHttp.get(DOUYIN_COMINORM, {
      status: this.state.currentIndex < 0 ? '' : this.state.currentIndex,
      page: this.page,
      length: 10
    })
    if (tableData && tableData.data) {
      this.total = tableData.recordsTotal
      if (this.page * 10 < this.total) {
        this.setState({loadMoreStatus: 'more'})
      } else {
        this.setState({loadMoreStatus: 'noMore'})
      }
      return tableData.data
    } else {
      this.setState({loadMoreStatus: 'noMore'})
    }
    return []
  }

  page = 1
  total = 0

  async onReachBottom() {
    if (this.page * 10 < this.total) {
      this.setState({loadMoreStatus: 'loading'})
      this.page++
      const tableData = await this.getData()
      const old = this.state.tableData
      if (tableData) {
        this.setState({tableData: [...old, ...tableData]})
      }
    }
  }

  categoryListClick(currentIndex) {
    try {
      if (this.state.currentIndex === currentIndex) {
        return false
      }
      Taro.showLoading({title: '加载中...'});
      this.page = 1
      this.setState({currentIndex, loadMoreStatus: 'loading', tableData: []}, async () => {
        const tableData = await this.getData()
        this.setState({tableData})
        Taro.hideLoading()
      })
    } catch (e) {
      Taro.hideLoading()
    }
  }

  withdraw() {

  }

  // 格式化接口返回的日期
  getDateInfo(value) {
    if (!value) {
      return ''
    }
    const date = new Date(value)
    const y = date.getFullYear()
    let MM = date.getMonth() + 1
    MM = MM < 10 ? ('0' + MM) : MM
    let d = date.getDate()
    d = d < 10 ? ('0' + d) : d
    let h = date.getHours()
    h = h < 10 ? ('0' + h) : h
    let m = date.getMinutes()
    m = m < 10 ? ('0' + m) : m
    let s = date.getSeconds()
    s = s < 10 ? ('0' + s) : s
    return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
  }

  async submit(item) {
    await Taro.showLoading({title: '加载中...', mask: true})
    const data = await newHttp.catchPost('/msvc-shop/v1/douyin/comput', {id: item.id})
    Taro.hideLoading()
    Taro.showToast({
      title: data.data,
      icon: 'none',
      mask: true
    });
    const tableData = await this.getData()
    this.setState({tableData})
  }

  render() {
    const {loadMoreStatus, tableData, groupList, currentIndex} = this.state
    return (
      <View className='businessListing-page regional-category'>
        <GzhAuth />
        {groupList.length > 0 &&
          <ScrollView scrollWithAnimation enable-flex scrollX className='scroll-view' style='margin-bottom: 15px;'>
            <View className='regional-category-nav'>
              {
                groupList.map((item, index) => (
                  <View className='regional-category-nav-item' key={index}
                    onClick={this.categoryListClick.bind(this, groupList[index].status)}
                  >
                    <View
                      className={`regional-category-nav-item-name ${currentIndex === groupList[index].status ? 'active' : ''}`}
                    >{groupList[index].mis}</View>
                    {currentIndex === groupList[index].status && <View className='active-line' />}
                    {currentIndex !== groupList[index].status &&
                      <View className='active-line' style='visibility: hidden;' />}
                  </View>
                ))
              }
            </View>
          </ScrollView>
        }
        {tableData.length > 0 && <View className='businessListing-content'>
          {tableData.length > 0 && tableData.map((item, index) =>
            <View className='businessListing-item' key={index}>
              <View className='title-box'>
                <View className='title-box-status'>
                  <Text
                    className={`${item.status == 1 ? 'successColor' : item.status == 2 ? 'errorColor' : 'yellowColor'}`}
                  >
                    {groupList[Number(item.status) + 1].mis}
                  </Text>
                </View>
                <View className='title'>{item.name || ''}</View>
                <View className='line' />
                <View className='bd-lk-id'>创建时间：{this.getDateInfo(item.add_date || '')}</View>
                <View className='bd-lk-id'>所属商家：{item.vname}</View>
                <View className='detail-view'>
                  {item.status != 0 && <View className='detail-btn' onClick={() => {
                    Taro.navigateTo({url: '/other/aliLocalLife/productInfo?gid=' + item.id + '&openType=edit'})
                  }}
                  >修改</View>}
                  {(item.status != 0 && item.status != 1) && <View className='detail-btn'
                    onClick={() => this.submit(item)}
                  >提审</View>}
                  <View className='detail-btn' onClick={() => {
                    Taro.navigateTo({url: '/other/aliLocalLife/productInfo?gid=' + item.id + '&openType=view'})
                  }}
                  >详情</View>
                </View>
              </View>
            </View>
          )}
        </View>}
        <View
          className={process.env.TARO_ENV === 'h5' ? "addInfo h5-small" : "addInfo"}
          style={`background-color: ${process.env.mainColor}`}
          onClick={() => Taro.navigateTo({url: `/other/aliLocalLife/productInfo`})}
        >
          增加产品信息 +
        </View>
        {loadMoreStatus !== 'loading' && tableData.length <= 0 && <View className='listNull'>
          <Image src={`${RESOURCE_URL}/resources/images/shopnull.png`} mode='widthFix' />
          <View className='text'>什么都没有,去看看别的吧~</View>
        </View>}
      </View>
    )
  }
}
